package com.hins.mq.orderMq;

import com.hins.mq.common.CommUtil;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConsumerC {
    private static Map<String, Integer> gosProfitMap = new HashMap<String, Integer>();

    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("other_consumer_group");
        consumer.setNamesrvAddr("192.168.0.111:9876");
        /**
         * -设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
         * -如果非第一次启动，那么按照上次消费的位置继续消费
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.subscribe("payFinishTopicTest", "other");
//        consumer.setConsumeThreadMin(1);
//        consumer.setConsumeThreadMax(1); // 这个设置最大线程数
        consumer.registerMessageListener(new MessageListenerOrderly() {

            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                context.setAutoCommit(true);

                for (MessageExt msg : msgs) {
                    try {
                        // 可以看到每个queue有唯一的consume线程来消费, 订单对每个queue(分区)有序
                        System.out.println(
                                "consumeThread=" + Thread.currentThread().getName() + " queueId=" + msg.getQueueId() + ", content:" + CommUtil.BytesToObject(msg.getBody()));
//                    System.out.println(msg);
//                        int i = 1 / 0;
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                    }
//                    System.out.println();
                }

                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();

        System.out.println("Consumer Started.");
    }
}
